package com.jpemartin.jgt;

import java.util.*;
import java.awt.Rectangle;

/** static methods for detecting collisions **/
public class CollisionDetection {
    /** given two lists of rectangles, gives a list
     *  of all pairs that intersect.
     *  This function does not require any of the two lists
     *  to be sorted (but it's a bit slow)
     *  
     *  The two lists don't need to be the same type, but
     *  they must both be collections of something that extends Rectangle and
     *  if they differ then the second one should be a subclass of the first one.
     *  
     *  We return a pair of lists instead of a list of pairs
     *  to limit the number of objects we create (for performance)
     *  
     *  If there's no collision, this may return either a pair of empty lists
     *  or a null pointer.
     **/
    static public <T extends Rectangle, U extends Collection<T>, V extends T, W extends Collection<V>> Pair<List<T>> findCollisionListSlow(U a, W b) {
        List<T> ia = null;
        List<T> ib = null;
        // invariant: (null==ans) iff (ia=ib=null)
        Pair<List<T>> ans = null;
        for (T r : a) {
            for (T s : b) {
                if (r.intersects(s)) {
                    if (null==ans) {
                       // lazy create
                       ia = new ArrayList<T>();
                       ib = new ArrayList<T>();
                       ans = new Pair<List<T>>(ia,ib);
                    }
                    ia.add(r);
                    ib.add(s);
                }
            }
        }
        return ans;
    }
    
}
